<?php

namespace App\Http\Controllers\Client\Activity\Talent;

use App\Http\Controllers\ClientController;
use App\Models\Common\Common;
use App\Models\Common\File;
use App\Models\Tools\Data;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class WinnerConfirmController extends ClientController
{
    /**
     * 预中奖人领奖
     */
    public function index()
    {


        $all = $this->all;
        /**
         * 验证参数
         */
        try {
            if (!isset($all['act_id'])) {
                throw new \Exception('缺少参数:act_id');
            }
            if (!isset($all['img'])) {
                throw new \Exception('缺少参数:img');
            }
            // 查询当前用户是否已经上传了二维码
            $qr_code = DB::table('talent')->where('we_id','=',$this->we_id)->value('collection_qr_code');
            if(is_null($qr_code) && !isset($all['collection_qr_code'])){
                throw new \Exception('缺少参数:collection_qr_code');
            }
        } catch (\Exception $e) {
            Log::error(WinnerConfirmController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1, '缺少参数');
        }

        $act_id = $all['act_id'];
        $img = $all['img'];

        /**
         * 图片上传
         */
        try {
            // 保存图片
            $img = File::saveMedia($img, 'images/talent/' . $this->we_id);
            if(is_null($qr_code)){
                $qr_code = File::saveMedia($all['collection_qr_code'], 'images/talent/' . $this->we_id);
                DB::table('talent')->where('we_id','=',$this->we_id)->update([
                    'collection_qr_code'=>$qr_code,
                ]);
            }
        } catch (\Exception $e) {
            Log::error(WinnerConfirmController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            if ($e->getMessage() === '读取上传图片失败') {
                return $this->setReturnJson(-1, 'pc端无法上传图片');
            }
            return $this->setReturnJson(-1, '图片上传失败，请联系人工客服处理');
        }

        try {
            DB::beginTransaction();
            // 查询活动信息
            $activity = DB::table('lottery_activity')->where('act_id', '=', $act_id)->lockForUpdate()->first();
            $activity = json_decode(json_encode($activity), true);

            // 检查活动状态:已取消直接结束
            if ($activity['status'] === Data::DATA_DB_LOTTERY_ACTIVITY_STATUS_CANCEL) {
                DB::rollBack();
                Log::error('霸王餐活动开奖：活动已取消', $activity);
                return $this->setReturnJson(-1, "领取失败，活动已关闭");
            }
            if ($activity['status'] !== Data::DATA_DB_LOTTERY_ACTIVITY_STATUS_PRE) {
                DB::rollBack();
                Log::error('霸王餐活动开奖：活动已取消', $activity);
                return $this->setReturnJson(-1, "领取失败，活动已开奖");
            }
            if ($activity['is_stop']) {
                DB::rollBack();
                Log::error('霸王餐活动开奖：活动被关闭', $activity);
                return $this->setReturnJson(-1, "领取失败，活动已关闭");
            }

            // 参与信息
            $participate = DB::table('lottery_users_draw')
                ->where('act_id', '=', $act_id)
                ->where('we_id', '=', $this->we_id)
                ->lockForUpdate()
                ->first();
            $participate = json_decode(json_encode($participate), true);

            if($participate['status'] === Data::DATA_DB_LOTTERY_USERS_DRAW_STATUS_OVERTIME){
                DB::rollBack();
                return $this->setReturnJson(-1,"领取失败，接受开奖超时");
            }

            if($participate['status'] !== Data::DATA_DB_LOTTERY_USERS_DRAW_STATUS_WINING){
                DB::rollBack();
                return $this->setReturnJson(-1,"领取失败");
            }


            // 更新活动状态
            DB::table('lottery_activity')->where('act_id','=',$act_id)->update([
                'status'=>Data::DATA_DB_LOTTERY_ACTIVITY_STATUS_AFTER,
                'draw_time'=>date('Y-m-d H:i:s'),
            ]);
            // 更新其他达人状态
            DB::table('lottery_users_draw')
                ->where('act_id','=',$act_id)
                ->where('status','=',Data::DATA_DB_LOTTERY_USERS_DRAW_STATUS_BEFORE)
                ->update(['status'=>Data::DATA_DB_LOTTERY_USERS_DRAW_STATUS_FAILED]);
            // 更新中奖达人状态
            DB::table('lottery_users_draw')->where('participate_id','=',$participate)->update([
                'status'=>Data::DATA_DB_LOTTERY_USERS_DRAW_STATUS_WIN,
                'confirmed_at'=>date('Y-m-d H:i:s'),
            ]);
            // 记录中奖信息
            DB::table('lottery_draw_detail')->insert([
                'participate_id'=>$participate['participate_id'],
                'act_id'=>$act_id,
                'we_id'=>$this->we_id,
                'buy_img'=>$img,
            ]);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error(WinnerConfirmController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1, '提交失败');
        }
        self::sendWinnerMessage($act_id);
        return $this->setReturnJson(0, '领取成功');


    }

    /**
     * 发送中奖信息
     * @param $act_id
     */
    protected static function sendWinnerMessage($act_id)
    {
        // 发送中奖人信息
        $message = DB::table('lottery_draw_detail as ldd')
            ->leftJoin('lottery_activity as la', 'ldd.act_id', '=', 'la.act_id')
            ->leftJoin('lottery_goods as lg', 'la.goods_id', '=', 'lg.goods_id')
            ->leftJoin('lottery_users as lu', 'ldd.we_id', '=', 'lu.we_id')
            ->where('la.act_id', '=', $act_id)
            ->select('la.act_no', 'lg.goods_name', 'ldd.participate_id', 'lu.openid')
            ->first();
        $message = json_decode(json_encode($message), true);
        $data = [
            'first' => '您已成功领取来飞网-霸王餐奖品，请及时到店体验',
            'keyword1' => [
                'value' => '霸王餐：' . $message['act_no'] . ' 期',
                'color' => '#F00'
            ],
            'keyword2' => $message['goods_name'],
            'keyword3' => '-',
            'keyword4' => '开奖后14天内',
            'remark' => '',
        ];
        Common::sendLaifeiMessage($message['openid'], 'win', $data, '/lottery/mine?active=2');


        // 发送商家信息
        $activity = DB::table('lottery_activity')->where('act_id','=',$act_id)->first();
        $activity = json_decode(json_encode($activity), true);
        // 查询商品信息
        $goods_message = DB::table('lottery_goods')->where('goods_id','=',$activity['goods_id'])->first();
        $goods_message = json_decode(json_encode($goods_message), true);
        $winner = DB::table('lottery_draw_detail as ldd')
            ->leftJoin('lottery_users as lu','ldd.we_id','=','lu.we_id')
            ->where('act_id','=',$act_id)
            ->value('nickname');
        $data = [
            'first' => '您发布的霸王餐已开奖。',
            'keyword1' => $goods_message['goods_name'],
            'keyword2' => $goods_message['price'],
            'keyword3' => $winner,
            'keyword4' => date('Y-m-d H:i:s'),
            'remark' => [
                'value' => '达人将在14天内光临您的店铺，请通知店铺相关工作人员。',
                'color' => '#F00'
            ],
        ];
        $openid = DB::table('lottery_users')->where('we_id','=',$activity['creator'])->value('openid');
        Common::sendLaifeiMessage($openid, 'open', $data, '/history');

    }

}
